<template>
  <div
    ref="editorDOM"
    class="text-editor"
  />
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue'
import E from 'wangeditor'

export default defineComponent({
  name: 'TextEditor',
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue'],
  setup (props, { emit }) {
    const editorDOM = ref(null)
    const initEditor = () => {
      console.log(editorDOM)
      const editor = new E(editorDOM.value as any)
      // 注意：事件监听必须在 create 之前
      editor.config.onchange = (value: string) => {
        emit('update:modelValue', value)
      }
      editor.create()
      // 注意：设置初始化必须在 create 之后
      editor.txt.html(props.modelValue)
    }

    onMounted(initEditor)

    return {
      editorDOM
    }
  }
  // 组件已经渲染好，可以初始化操作 DOM 了
})
</script>

<style lang="scss" scoped></style>
